package com.zhj.user.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zhj.common.util.id.Sid;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableConfigurationProperties(WxConfig.class)
public class ApplicationAutoConfiguration {

    /**
     * 生成用户id工具类
     * @return Sid
     */
    @Bean
    public Sid sid() {
        return new Sid();
    }

    /**
     * 添加 mybatis-plus 分页插件，返回一个拦截器
     * @return MybatisPlusInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 手动创建 RestTemplate
     * @return
     */
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        messageConverters.forEach(converter -> {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                List<MediaType> mediaTypes = new ArrayList<>(converter.getSupportedMediaTypes());
                //设置当前两种类型，用于微信授权登录时，返回 TEXT_HTML 类型时找不到解析类
                mediaTypes.add(MediaType.TEXT_HTML);
                mediaTypes.add(MediaType.TEXT_PLAIN);
                ((MappingJackson2HttpMessageConverter) converter).setSupportedMediaTypes(mediaTypes);
            }
        });
        return restTemplate;
    }

}
